<template>
  <div>
    <!-- 表单 -->
    <el-form size="small" :model="queryParams" :inline="true">
      <el-form-item label="菜单名称">
        <el-input v-model="queryParams.name" placeholder="请输入 菜单名称" style="width:200px;" clearable></el-input>
      </el-form-item>
      <el-form-item label="菜单编号">
        <el-input v-model="queryParams.orderNum" placeholder="请输入 菜单编号" style="width:200px;" clearable></el-input>
      </el-form-item>
      <el-form-item label="菜单别名">
        <el-input v-model="queryParams.roleName" placeholder="请输入 菜单别名" style="width:200px;" clearable></el-input>
      </el-form-item>
      <el-button size="small" class="search_button" type="primary" icon="el-icon-search"
        @click="getMenuList">查询</el-button>
      <el-button size="small" plain class="reset_button" icon="el-icon-refresh" @click="reset">重置</el-button>
    </el-form>

    <el-row>
      <el-button size="small" type="primary" icon="el-icon-folder-add" @click="showAdd">新增</el-button>
      <el-button size="small" plain type="danger" icon="el-icon-delete">删除</el-button>
      <el-button size="small" type="info" icon="el-icon-sort" plain @click="toggleExpandAll">展开/折叠</el-button>
    </el-row>


    <!-- 表格 -->
    <el-table size="medium" v-if="refreshTable" ref="multipleTable" :data="tableData" style="width: 100%;margin-top:10px"
      border row-key="id" :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column type="selection" align="center" width="55"></el-table-column>
      <!-- <el-table-column prop="" label="#" align="center" width="55"></el-table-column> -->
      <el-table-column prop="name" label="菜单名称" align="center" min-width="160"></el-table-column>
      <el-table-column prop="path" label="路由地址" align="center" min-width="200"></el-table-column>
      <el-table-column prop="icon" label="菜单图标" align="center" width="80">
        <template slot-scope="scope">
          <i :class="scope.row.icon"></i>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="" label="菜单编号" align="center"></el-table-column> -->
      <el-table-column prop="type" label="菜单类型" align="center" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.type == 1">目录</span>
          <span v-if="scope.row.type == 2">菜单</span>
          <span v-if="scope.row.type == 3">按钮</span>
          <span v-if="scope.row.type == 4">小程序</span>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="" label="新窗口" align="center"></el-table-column> -->
      <el-table-column prop="component" label="组件路径" align="center" min-width="300"></el-table-column>
      <el-table-column prop="orderNum" label="菜单排序" align="center" width="50"></el-table-column>
      <el-table-column prop="handle" label="操作" align="center" width="160">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" plain @click="showChange(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" plain @click="deleteMenu({ id: scope.row.id })">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24" v-if="form.type != '4'">
            <el-form-item label="上级菜单" prop="parentId">
              <el-cascader :value="form.parentId" ref="cascaderArr" :options="menuOptionsPC" :show-all-levels="false"
                :props="defaultProps" clearable @change="handleChange($event)" style="width: 100%;"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.type == '4'">
            <el-form-item label="上级菜单" prop="parentId">
              <el-cascader :value="form.parentId" ref="cascaderArr" :options="menuOptionsMObile" :show-all-levels="false"
                :props="defaultProps" clearable @change="handleChange($event)" style="width: 100%;"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="type">
              <el-radio-group v-model="form.type" clearable>
                <el-radio label="1">目录</el-radio>
                <el-radio label="2">菜单</el-radio>
                <el-radio label="3">按钮</el-radio>
                <el-radio label="4">小程序</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.type == '1' || form.type == '2'">
            <el-form-item label="菜单图标">
              <el-input :value="form.icon" placeholder="点击选择图标" readonly @click.native="showIcon" style="width: 500px;">
              </el-input>
              <div id="showIcon">
                <i :class="form.icon" />
              </div>
              <div id="removeIcon" v-show="form.icon">
                <i class="el-icon-circle-close" @click="removeIcon" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入菜单名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type == '1' || form.type == '2'">
            <el-form-item>
              <span slot="label">
                <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                是否外链
              </span>
              <el-radio-group v-model="form.isFrame">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type == '1' || form.type == '2'">
            <el-form-item prop="path">
              <span slot="label">
                <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                路由地址
              </span>
              <el-input v-model="form.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type == '2' || form.type == '4'">
            <el-form-item>
              <span slot="label">
                <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                组件路径
              </span>
              <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type == '4'">
            <el-form-item label="图标路径" prop="icon">
              <el-input v-model="form.icon" placeholder="请输入图标路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type == '3' || form.type == '2'">
            <el-form-item prop="perms">
              <el-input v-model="form.perms" placeholder="请输入权限标识" maxlength="100" clearable />
              <span slot="label">
                <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                权限字符
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type == '2'">
            <el-form-item>
              <el-input v-model="form.query" placeholder="请输入路由参数" maxlength="255" clearable />
              <span slot="label">
                <el-tooltip content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`' placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                路由参数
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type == '2'">
            <el-form-item>
              <span slot="label">
                <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                是否缓存
              </span>
              <el-radio-group v-model="form.isCache">
                <el-radio label="0">缓存</el-radio>
                <el-radio label="1">不缓存</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12" v-if="form.type == '1' || form.type == '2'">
            <el-form-item>
              <span slot="label">
                <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                显示状态
              </span>
              <el-radio-group v-model="form.visible">
                <el-radio label="0">显示</el-radio>
                <el-radio label="1">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12" v-if="form.type == '1'||form.type == '2'">
            <el-form-item prop="status">
              <span slot="label">
                <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                菜单状态
              </span>
              <el-radio-group v-model="form.status">
                <el-radio label="">正常</el-radio>
                <el-radio label="">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit('ruleForm')">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog title="请选择菜单图标" :visible.sync="showIconList" width="800px" append-to-body>
      <el-tabs v-model="activeName">
        <el-tab-pane label="线框风格" name="thin">
          <div id="iconBox">
            <div id="iconBoxItem" @click="comfirmIcon(item)" @mouseenter="bigIcon(item)" @mouseleave="rebackIcon(item)"
              v-for="item in iconListThin" :key="item.index">
              <i :class="item" :id="item"></i>
              <span :id="item + text">{{ item }}</span>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="实底风格" name="strong">
          <div id="iconBox">
            <div id="iconBoxItem" @click="comfirmIcon(item)" @mouseenter="bigIcon(item)" @mouseleave="rebackIcon(item)"
              v-for="item in iconListStrong" :key="item.index">
              <i :class="item" :id="item"></i>
              <span :id="item + text">{{ item }}</span>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>


    <!-- <el-pagination class="pagination" background layout="total, sizes, prev, pager, next, jumper" :total="total"
      :page-size="10" :page-sizes="[10, 20, 30, 40]" @current-change="handleCurrentChange"
      @size-change="handleSizeChange"></el-pagination> -->
  </div>
</template>

<script>
import {
  getMenuList,
  addMenu, //添加菜单
  changeMenu, //修改菜单
  deleteMenu, //删除菜单
} from '_api/MenuManage/index.js'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
export default {
  components: { Treeselect, IconSelect },
  data() {
    return {
      activeName: "thin",
      text: "text",
      defaultProps: {
        children: "children",
        label: "name",
        value: "id",
        checkStrictly: true
      },
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        component: "",
        current: 0,
        field: "",
        hidden: "",
        icon: "",
        id: "",
        keepAlive: "",
        name: "",
        order: "",
        pageSize: 100,
        parentId: "",
        path: "",
        perms: "",
        redirect: "",
        sortIndex: "",
        title: "",
        type: ""
      },
      form: {
        component: "",
        createBy: "",
        createTime: "",
        deleted: "",
        icon: "",
        id: "",
        isCache: "0",
        isFrame: "1",
        modifyBy: "",
        modifyTime: "",
        name: "",
        orderNum: "",
        parentId: "",
        path: "",
        perms: "",
        query: "",
        remark: "",
        type: "1",
        version: "",
        visible: "0"
      },
      tableData: [],
      open: false,
      showIconList: false,
      // 菜单树选项
      menuOptionsPC: [],
      menuOptionsMObile: [],
      total: 0,
      // 弹出层标题
      title: "",
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级菜单不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "菜单类型不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" }
        ],
        path: [
          { required: true, message: "路由地址不能为空", trigger: "blur" }
        ],
        perms: [
          { required: true, message: "权限字符不能为空", trigger: "blur" }
        ]
      },
      iconListStrong: ["el-icon-platform-eleme", "el-icon-eleme", "el-icon-delete-solid", "el-icon-phone", "el-icon-more", "el-icon-star-on", "el-icon-s-goods", "el-icon-s-cooperation", "el-icon-s-order", "el-icon-s-comment", "el-icon-s-custom", "el-icon-menu", "el-icon-s-data"],
      iconListThin: ["el-icon-setting", "el-icon-user", "el-icon-phone-outline", "el-icon-star-off", "el-icon-goods", "el-icon-camera", "el-icon-video-camera", "el-icon-view", "el-icon-c-scale-to-original", "el-icon-date", "el-icon-edit-outline", "el-icon-folder", "el-icon-document-copy", "el-icon-takeaway-box", "el-icon-monitor", "el-icon-office-building", "el-icon-school", "el-icon-house", "el-icon-money"]
    }
  },
  methods: {
    // 删除图标
    removeIcon() {
      this.form.icon = ""
    },
    showIcon() {
      this.showIconList = true
    },
    // 放大
    bigIcon(e) {
      document.getElementById(e).style.fontSize = "50px"
      document.getElementById(e + this.text).style.fontSize = "18px"
    },
    // 回复
    rebackIcon(e) {
      document.getElementById(e).style.fontSize = "30px"
      document.getElementById(e + this.text).style.fontSize = "14px"
    },
    // 选择图标
    comfirmIcon(e) {
      this.form.icon = e
      this.showIconList = false
    },
    showAdd() {
      this.resetForm();
      this.open = true
      this.title = "新增菜单"
    },
    showChange(row) {
      this.resetForm();
      this.open = true
      this.title = "修改菜单"
      console.log(row);
      this.form = row
      this.form.type = row.type.toString()
      this.form.isCache = row.isCache.toString()
      this.form.isFrame = row.isFrame.toString()
      // this.getParentsById(this.menuOptions, row.parentId)
    },
    // 提交
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            changeMenu(this.form).then(res => {
              if (res.data.success == true) {
                this.open = false
                this.$message({
                  message: '修改成功!',
                  duration: 1000,
                  type: 'success',
                  onClose: () => {
                    this.reset()
                  }
                })
              }
            })
          } else {
            // console.log(this.getMenuAllCheckedKeys());
            addMenu(this.form).then(res => {
              if (res.data.success == true) {
                this.open = false
                this.$message({
                  message: '添加成功!',
                  duration: 1000,
                  type: 'success',
                  onClose: () => {
                    this.reset()
                  }
                })
              }
            })
          }
        } else {
          return false;
        }
      });
    },
    // 删除菜单
    deleteMenu(e) {
      this.$confirm('此操作将删除该菜单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteMenu(e).then(res => {
          if (res.data.success == true) {
            this.$message({
              message: '删除成功!',
              duration: 1000,
              type: 'success',
              onClose: () => {
                this.reset()
              }
            })
          } else {
            this.$message.info(res.data.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleChange(row) {
      const checkedNode = this.$refs["cascaderArr"].getCheckedNodes();
      console.log(checkedNode[0].data.id);  //获取当前点击节点的id
      this.form.parentId = checkedNode[0].data.id
    },
    // 选择图标
    selected(name) {
      this.form.icon = name;
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    // 重置表单
    resetForm() {
      this.form = {
        component: "",
        createBy: "",
        createTime: "",
        deleted: "",
        icon: "",
        id: "",
        isCache: "0",
        isFrame: "1",
        modifyBy: "",
        modifyTime: "",
        name: "",
        orderNum: "",
        parentId: "",
        path: "",
        perms: "",
        query: "",
        remark: "",
        type: "1",
        version: "",
        visible: "0"
      }
    },
    // 重置按钮
    reset() {
      this.queryParams = {
        component: "",
        current: 0,
        field: "",
        hidden: "",
        icon: "",
        id: "",
        keepAlive: "",
        name: "",
        order: "",
        pageSize: 100,
        parentId: "",
        path: "",
        perms: "",
        redirect: "",
        sortIndex: "",
        title: "",
        type: ""
      }
      this.getMenuList()
    },
    handleCurrentChange(e) {
      //当前页
      this.queryParams.current = e
      this.getMenuList()
    },
    handleSizeChange(e) {
      this.queryParams.pageSize = e
      this.getMenuList()
    },
    //查询菜单列表
    getMenuList() {
      getMenuList(this.queryParams).then(res => {
        // console.log(res)
        if (res.data.success == true) {
          this.tableData = res.data.data.list
          this.total = res.data.data.total
          this.queryParams.type = 0
          getMenuList(this.queryParams).then(res => {
            this.menuOptionsPC = []
            const menu = { id: 0, name: 'PC根目录', children: [] }
            menu.children = res.data.data.list
            this.menuOptionsPC.push(menu)
            this.queryParams.type = 4
            getMenuList(this.queryParams).then(res => {
              this.menuOptionsMObile = []
              const menu = { id: 0, name: '小程序根目录', children: [] }
              menu.children = res.data.data.list
              this.menuOptionsMObile.push(menu)
            })
          })
        } else {
          this.$message.info(res.data.message)
        }
      }).catch(error => {
        // console.log(error.response.status);
        // if (error.response.status == 401) {
        //   this.$confirm('登录状态过期, 请重新登录!', '提示', {
        //     confirmButtonText: '确定',
        //     // cancelButtonText: '取消',
        //     showCancelButton: false,
        //     type: 'warning'
        //   }).then(() => {
        //     this.$router.push('/login')
        //   }).catch(() => {

        //   })
        // }
      })
    }
  },
  created() {
    this.getMenuList()
  },
};
</script>
<style lang="scss" scoped>
.pagination {
  float: right;
  margin-top: 10px;
}

.search_button {
  margin-left: 80px;
}

.reset_button {
  margin-left: 10px;
}

/* tree border */
.tree-border {
  width: 330px;
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  background: #FFFFFF none;
  border-radius: 4px;
}

.btnBox {
  display: flex;
  width: 410px;
  justify-content: space-between;
  position: relative;
  left: calc(50% - 205px);
  padding-bottom: 20px;
}

.btnBox_item {
  width: 200px;
}

#iconBox {
  display: flex;
  flex-wrap: wrap;
}

#iconBoxItem {
  width: 100px;
  height: 120px;
  display: flex;
  align-items: center;
  // justify-content: center;
  flex-direction: column;
  margin-right: 20px;
  // border: 1px solid black;
}

#iconBoxItem i {
  font-size: 30px;
  margin-top: 20px;
}

#iconBoxItem span {
  font-size: 14px;
  text-align: center;
}

#showIcon {
  width: 50px;
  height: 32px;
  background-color: #e2dbdb;
  position: absolute;
  right: 10px;
  top: 0;
  text-align: center;
  line-height: 40px;
}

#showIcon i {
  font-size: 24px;
}

#removeIcon {
  position: absolute;
  right: 74px;
  top: 0;
}

#removeIcon i {
  font-size: 16px;
}
</style>
